<template>
  <div class="chatPage">
    <!-- 聊天界面头部 -->
    <page-header @toLastPage="toLastPage">
      <template v-slot:title v-if=groupInf>
       {{groupInf.beizhu?groupInf.beizhu:groupInf.name}}({{groupInf.count}})
       <div v-if="groupInf.beizhu" class="groupName">
         {{groupInf.name}}
       </div>
      </template>
      <template v-slot:right>
        <div @click="toDetail">
          ...
        </div>
      </template>
    </page-header>
    <!-- 聊天界面 -->
    <div class="content" ref="content" :style="'transform:translateY('+contentY+');'">
     <div>
        <div v-for="(item,index) in messageList" :key="index">
          <chat-item :chatItem=item :chatIndex=index :pretime="index>0?messageList[index-1].M_Time:0" :listY=listY @remake='remake' :isShowName='showName'></chat-item>
     </div>
     </div>
    </div>
    <!-- 弹出框蒙版 -->
    <div class="mask" v-if="boardStatus" @click="closeBoard"></div>
    <!-- 聊天界面底部 -->
    <div class="footer">
      <div class="bottom-box flex">
      <div class="f-left" @click="changeChatEvent">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-yuyin"></use>
        </svg>
      </div>
      <div class="f-center f-1">
        <input type="text" v-show="!changeChatState" v-model="chatContent"/>
        <button v-show="changeChatState">按住 说话</button>
      </div>
      <div class="f-right flex" :style="'width:'+rightWidth+';'">
           <svg class="icon" aria-hidden="true" @click="showBoard('face')">
          <use xlink:href="#icon-biaoqing1"></use>
        </svg>
        <svg class="icon" aria-hidden="true" v-if="!sendStatus" @click="showBoard('operation')">
          <use xlink:href="#icon--tainjia"></use>
        </svg>
        <button v-if="sendStatus" @click="sendMsg('text')">发送</button>
      </div>
    </div>
     <!-- 底部弹出框 -->
    <div class="board" v-if="boardStatus">
      <van-swipe class="my-swipe" :stop-propagation="false"  :loop="false" indicator-color='#696969' ref='boardSwipe'>
        <!-- 操作菜单 -->
        <van-swipe-item class="flex"  v-for="i in swipeList" :key="i">
          <div class="item-wrapper" v-for="(item,index) in boardList" :key="index">
            <div :class="boardState==='operation'?'icon-wrapper-operation':'icon-wrapper-face' " v-if="index>=(i-1)*8&&index<=i*8-1">
          <!-- 相册 -->
          <van-uploader v-if="index===0&&boardState==='operation'" :after-read="afterRead" multiple>
            <svg class="icon" aria-hidden="true"   @click="operateEvent(item.event)">
           <use :xlink:href="item.icon"></use>
        </svg>
          </van-uploader>
               <svg class="icon" aria-hidden="true"   @click="operateEvent(item.event)" v-else-if="boardState==='operation'&&index>0">
           <use :xlink:href="item.icon"></use>
        </svg>
        <van-image
        width="2.5rem"
        height="2.5rem"
        fit="cover"
        lazy-load
        :src="item.imgUrl"
        v-else
        @click="sendMsg('face',index)"
        />
        <div class="text">{{item.text}}</div>
          </div>
          </div>
        </van-swipe-item>
</van-swipe>
    </div>
</div> 
        <loading v-if="showLoading"></loading>
  </div>
</template>
<script>
import BScroll from "better-scroll";
import chatItem from "./chatItem";
import pageHeader from '../common/pageHeader';
import loading from '../common/loading';
import {Meteor} from 'meteor/meteor';
import upload from '../../../api/libs/upload';
import { image, user,messages,friends, group, groupUser } from '../../../api/collections/index';
export default {
  data() {
    return {
      // 改变聊天状态：语音/文字
      changeChatState: false,
      // 滚动的Y轴长度
      listY:0,
      // 聊天内容
      chatContent:'',
      // 发送按钮显示隐藏
      sendStatus:false,
      // 底部输入框右边宽度
      rightWidth:'2rem',
      // 底部弹出框状态
      boardStatus:false,
      // 是否首次打开底部弹出框
      isFirstBoardOpen:true,
      contentY:0,
      // 表情包列表
      faceList:[
        {
          id:'01',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/6d519b57a876e2ac4ca613cc9c91efb1f99157469c3a6434.gif',
          text:'快活啊'
        },
         {
          id:'02',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/ea8826f2a05dbee6ea840e21cd4af83eecc2e39732db1ff0.gif',
          text:'爱了爱了'
        },
         {
          id:'03',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/ad2b96f959732d56215c6ab698cbdfeaa19c2753176e1f74.gif',
          text:'游戏中'
        },
         {
          id:'04',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/cff43f2ea53d157ed7d910987af14e2854703a362d4790bc.gif',
          text:'有意思'
        },
         {
          id:'05',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/35e6869ec84e829f2a7c6109109282127713bc841f1ab1a7.gif',
          text:'受死吧'
        },
         {
          id:'06',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/ef5c4cdddfa0c0fdb1f79d312d87ade12cd5d7a257064454.gif',
          text:'有钱人'
        },
        {
          id:'07',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/fd53926e7f9ccbcdaffb7d41a0841c848f9a6698e3a006a8.gif',
          text:'快乐'
        },
        {
          id:'08',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/42cfd0e386969cd6bb1b8f7cafd44f969774e7bc3f984974.gif',
          text:'优秀'
        },
        {
          id:'09',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/b2310fe3f06cdb82b1f76bfe16e358ea15f6deca4806ac65.gif',
          text:'辣鸡'
        },
        {
          id:'10',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/b52bdf1740c5ecf2095aef2ab0fa4c0fcd987d36b7a214e0.gif',
          text:'哭了'
        },
        {
          id:'11',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/410cd89738b6ef994fdc28884e5cfd907b347dba0f131e53.gif',
          text:'造作啊'
        },
        {
          id:'12',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/b3404292913da90f5d2d5f88d2130ff1aae94e59b3c2082e.gif',
          text:'嘚瑟'
        },
        {
          id:'13',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/0b9ddb90890b8543d177296abb9ed407d74a743ca631bbeb.gif',
          text:'哈哈哈哈'
        },
        {
          id:'14',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/c82732d2aca178c03a890c885c27b0cde8d7e0536643cbb3.gif',
          text:'无数个赞'
        },
        {
          id:'15',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/09618f3ed8ed278155ca1d4670acad9c1d0682337c6ab498.gif',
          text:'对不起'
        },
        {
          id:'16',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/59ab6f3f4c8a97998e2f48379740dee3b5b5d8e977c00674.gif',
          text:'爱你哟'
        },
        {
          id:'17',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/410fd4d08a14c866347e33bc74de5d0e29af29ecab697bf5.gif',
          text:'大爷来玩啊'
        },
        {
          id:'18',
          imgUrl:'https://www.helloimg.com/images/2021/02/01/549f80283a75359e8f1865b7c88c6581c66653268b1df0cf.gif',
          text:'滚吧'
        }
      ],
      // 弹出面板内容
      boardList:[],
      // 弹出面板选项：表情包/操作菜单
      boardState:'',
      // 操作菜单内容
      operationList:[
        {
          icon:'#icon-photo',
          text:'相册',
          event:'photo'
        },
         {
          icon:'#icon-xiangji',
          text:'拍摄',
          event:''
        },
        {
          icon:'#icon-yuyintonghua',
          text:'视频通话',
          event:''
        },
        {
          icon:'#icon-weizhi',
          text:'位置',
          event:''
        },
        {
          icon:'#icon--hongbao',
          text:'红包',
          event:'packet'
        },
         {
          icon:'#icon-c',
          text:'转账',
          event:''
        },
        {
          icon:'#icon-yuyinshuru',
          text:'语音输入',
          event:''
        },
         {
          icon:'#icon-wodeshoucang',
          text:'我的收藏',
          event:''
        },
         {
          icon:'#icon-mingpian',
          text:'名片',
          event:''
        }
      ],
      userId:sessionStorage.getItem('user'),
      groupId:this.$route.params.id,
      showLoading:true
    };
  },
     meteor: {
    $subscribe: {
      'userInf': []
    },
    userInf(){
         const getUser = user.findOne({_id:this.userId})
        if(getUser){
             const avatar = image.findOne({_id:getUser.avatarId})
              avatar&&(getUser.avatar = avatar.base64)
        } 
        return getUser                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
    },
    showName(){
      const inf = groupUser.findOne({gid:this.groupId,userId:this.userId})
      if(inf){
        return inf.showGroupItemNIck
      }
    },
    groupInf(){
       const inf = group.findOne({_id:this.groupId})
       const mine = groupUser.findOne({gid:this.groupId,userId:this.userId})
       const userList = groupUser.find({gid:this.groupId}).fetch()
       if(inf&&mine&&userList){
         return {
           beizhu:mine.groupRemark,
           name:inf.g_name,
           count:userList.length
         }
       }
    },
    groupUserInf(){
      return groupUser.find({gid:this.groupId}).fetch()
    },
    allMsgList(){
      return messages.find({M_IsGroup:true,M_GroupId:this.groupId}).fetch()
    },
    messageList(){
     const list = messages.find({M_IsGroup:true,M_GroupId:this.groupId}).fetch()
     let newArr = []
    if(list&&list.length!==0){
      list.forEach((e,i) => {
        if(e.M_MessagesType=='invite'){
         let obj = e.M_PostMessages
        if(obj.inviteId == obj.inviteeId){
          const user1 = user.findOne({_id:obj.inviteId})
          if(user1){
            e.M_PostMessages = user1.nickname+'创建了群聊'
          }
        }else{
          const user1 = user.findOne({_id:obj.inviteId})
          const user2 = user.findOne({_id:obj.inviteeId})
          if(user1&&user2){
            e.M_PostMessages = '"'+user1.nickname+'"'+'邀请'+'"'+user2.nickname+'"'+'加入了群聊'
          }
        }
        newArr.push(e)
        }
        else{
          if(e.M_ToUserID==this.userId){
          if(e.M_FromUserID == this.userId){
          if(this.userInf){
            e.avatar = this.userInf.avatar
            const getGUser = groupUser.findOne({userId:e.M_FromUserID,gid:this.groupId})
            e.name = getGUser.groupName
            newArr.push(e)
          }
        }else{
          const getUser = user.findOne({_id:e.M_FromUserID})
          if(getUser){
            const avatar = image.findOne({_id:getUser.avatarId})
            if(avatar){
              e.avatar = avatar.base64
              const getGUser = groupUser.findOne({userId:e.M_FromUserID,gid:this.groupId})
             if(getGUser){
                e.name = getGUser.groupName
             }
             else{
               e.name = getUser.nickname
             }
               newArr.push(e)
            }
          }
        }
          }
        }
      })
      newArr.sort((e1,e2)=>{return e1.M_Time-e2.M_Time})
      return newArr
    }
    }
    },
  computed:{
    swipeList(){
      return Math.ceil(this.boardList.length/8)
    }
  },
  components: {
    chatItem,
    pageHeader,
    loading
  },
  mounted() {
    this.setScollView();
  },
  watch:{
    chatContent(){
      if(this.chatContent.trim().length>0){
        this.rightWidth='3rem'
        this.sendStatus=true
      }
      else{
        this.sendStatus=false
         this.rightWidth='2rem'
      }
    },
    boardStatus(){
      if(!this.boardStatus){
        this.boardState=''
        this.isFirstBoardOpen=true
      }
    },
    messageList(){
      this.$nextTick(()=>{
          this.scroll.refresh();
       // 自动滚到到底部
        this.scroll.scrollTo(0,this.scroll.maxScrollY)
        })
        this.showLoading = false
    }
  },
  // 销毁完成时
  destroyed(){
    Meteor.call('groupMsg.isReaded',{
      toid:this.userId,
      gid:this.groupId
    }),
    Meteor.call('indexMsg.updateCount',{
      userId:this.userId,
      otherId:this.groupId
    })
  },
  methods: {
    // 关闭弹出框
    closeBoard(){
      this.showBoard(this.boardState)
    },
    // 返回首页
    toLastPage() {
      this.$router.push("/home");
    },
    // 更改聊天方式:语音/文字
    changeChatEvent() {
      this.changeChatState = !this.changeChatState
    },
    // 打开弹出框
    showBoard(e){
       this.$nextTick(()=>{
          if(this.$refs.boardSwipe){
            this.$refs.boardSwipe.swipeTo(0,{immediate:false})
          }
        })
      if(this.boardState===e&&!this.isFirstBoardOpen||this.isFirstBoardOpen){
        this.boardStatus=!this.boardStatus
        this.isFirstBoardOpen=false
      }
      switch(e){
        case 'face':
          this.boardList=this.faceList;
          this.boardState='face'
          break;
        case 'operation':
          this.boardList=this.operationList;
          this.boardState = 'operation';
          break;
        default:break;
      }
      if(this.boardStatus===true){
        if(this.messageList.length>=5){
          this.contentY='-9rem'
        }else{
        this.contentY=0
        }
      }
      else{
        this.contentY=0
      }
    },
    // 设置聊天滚动
    setScollView() {
      this.$nextTick(() => {
        //$refs绑定元素
        if (!this.scroll) {
          this.scroll = new BScroll(this.$refs.content, {
            //开启点击事件 默认为false
            click: true,
            probeType:3
          });
        } else if (!this.$refs.content) {
          return;
        } else {
          this.scroll.refresh();
        }
          this.scroll.on('scrollEnd', (pos) => {
         this.listY=pos.y
          })
          // 自动滚到到底部
        this.scroll.scrollTo(0,this.scroll.maxScrollY)
      });
    },
    // 发送消息
    sendMsg(e,index){
       var obj = {
          M_PostMessages:'',
          M_Status:false,
          M_Time:new Date().getTime(),
          M_MessagesType:'text',
          M_FromUserID:this.userId,
          M_GroupId:this.groupId,
          M_IsGroup:true,
          M_ToUserID:''
      }
      switch(e){
        case 'text':obj.M_PostMessages=this.chatContent;
        this.groupUserInf.forEach(e=>{
          obj.M_ToUserID = e.userId
          this.sendText(obj);
        })
        this.chatContent = '';
        break;
        case 'face':obj.M_PostMessages=this.faceList[index].imgUrl;
        obj.M_MessagesType='face';
       this.groupUserInf.forEach(e=>{
          obj.M_ToUserID = e.userId
          this.sendText(obj);
        })
        break;
        case 'image':obj.M_PostMessages = index;
        obj.M_MessagesType = 'image';
        this.groupUserInf.forEach(e => {
           obj.M_ToUserID = e.userId
          this.sendText(obj);
        })
        default:break;
      }
    },
    // 发送文本
    sendText(e){
      let data = ''
      Meteor.call('message.create',e,(err,res)=>{
        if(err){
          this.$toast(err.error)
        }else{
            data = res
        }
      })
       setTimeout(()=>{
         if(this.groupUserInf){
          this.groupUserInf.forEach(e => {
          this.createIndexMsg(e.userId,this.groupId,data)
        })
       }
       },500)
    },
    // 建立首页消息表
    createIndexMsg(id1,id2,data){
        var msg = {
        I_UserId:id1,
        I_OtherId:id2,
        I_Type:'group',
        I_LastMsgId:data,
        I_isTop:false
      }
      var num = 0
      if(this.allMsgList){
        this.allMsgList.forEach((e) => {
        if( e.M_FromUserID !== id1 && e.M_ToUserID == id1 && e.M_MessagesType !== 'invite' && e.M_Status == false){
          num = num +1
        }
      })
       msg.I_noReadCount = num
      Meteor.call('indexMsg.create',msg) 
      }
    },
    remake(e){
     this.chatContent=this.list[e].data
    },
    operateEvent(e){
      switch(e){
        case 'photo':break;
        // case 'packet':this.$router.push('/setPacket');break;
        default:this.$notify({ type: 'success', message: '功能暂未开发',duration: 500 });break;
      }
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      if(file instanceof Array){
            this.upLoadLength = file.length
            file.forEach((e,i) => {
                upload.uploadImg(e,this.afterUpload)
            })
        }
        else{
            upload.uploadImg(file,this.afterUpload)
        } 
    },
       //上传图片成功后
    afterUpload(res){
         if(res){
           Meteor.call('image.find',res,(err,e) =>{
               if(err){
                   this.$toast(err.error)
               }
               else{
                   this.sendMsg('image',e.base64)
               }
           })
         }
    },
    // 跳转到聊天详情页
    toDetail(){
      this.$router.push('/chatDetail/'+this.groupId)
    }
  },
};
</script>
<style scoped>
.header {
  position: fixed;
  background-color: #ededed;
  left: 0;
  right: 0;
  top: 0;
  padding: 0 0.3rem;
  height: 1.5rem;
  z-index: 999;
}
.h-left {
  font-size: 0.6rem;
  line-height: 1.5rem;
}
.h-center {
  font-size: 0.6rem;
  margin-left: 0.3rem;
  line-height: 1.5rem;
  font-weight: 700;
}
.h-right {
  position: relative;
  bottom: 0.2rem;
  width: 1rem;
  text-align: right;
}
.content {
  position: absolute;
  left: 0;
  right: 0;
  top: 1.5rem;
  bottom: 2rem;
  overflow: hidden;
  /* background-color: #ff0000; */
}
.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: auto;
}
.bottom-box{
   background-color: #f7f7f7;
  box-sizing: border-box;
  height: 2rem;
   padding: 0.3rem;
   border-top: 1px solid #f7f7f7;
   border-bottom: 1px solid rgba(0,0,0,.1);
}
.f-left {
  width: 1rem;
  text-align: center;
  margin-top: 0.2rem;
}
.f-right {
  text-align: center;
}
.f-right button{
  background-color: #05C15F;
  font-size: .6rem;
  border-radius: .2rem;
  color: #fff;
}
.f-right .icon{
font-size: 1.4rem;
}
.f-right .icon:first-child {
  margin-right: 0.4rem;
}
.f-center {
  padding: 0 0.3rem;
}
input {
  background-color: #fff;
  border: none;
  width: 100%;
  padding: .1rem .2rem;
  caret-color: #00ff00;
  font-size: 0.6rem;
  height: 1.2rem;
  line-height: 1.2rem;
}
button {
  width: 100%;
  border: none;
  background-color: #fff;
  text-align: center;
  font-size: 0.6rem;
  height: 1.2rem;
  line-height: 1.2rem;
}
.board{
  height: 9rem;
  background-color: #F7F7F7;
}
  .my-swipe .van-swipe-item {
    color: #1E1E1E;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
  }
  .van-swipe-item{
    flex-wrap: wrap;
  }
  .item-wrapper{
    width: 25%;
    height: 50%;
  }
  .icon-wrapper-operation{
    box-sizing: border-box;
    padding: .6rem .5rem;
  }
  .icon-wrapper-face{
    padding: .3rem;
  }
  .icon-wrapper-operation .icon{
    text-align: center;
    background-color: #fff;
    padding: .5rem;
    border-radius: .5rem;
  }
  .text{
    font-size: .5rem;
    color: #808080;
  }
  .mask{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 11rem;
    z-index: 999;
  }
  .groupName{
    position: absolute;
    top:.65rem;
    left: 1.4rem;
    font-size: .5rem;
    color: #555;
  }
</style>